package com.magic.uschat.bean;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import cn.bmob.newim.bean.BmobIMConversation;

import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.DbUtils.DaoConfig;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;

public class DbManager {
	private static DbUtils db;
	private static DaoConfig config;

	private static DbManager instance = new DbManager();
	
	public static void init(Context context){
		config = new DaoConfig(context);
		config.setDbName("uschat_xutils.db");
		config.setDbVersion(1);
		db = DbUtils.create(config);
	}
	
	private DbManager(){}
	public static DbManager getManager(){
		return instance;
	}
	
	public static void saveFriend(Friends friend,String owenrId) throws DbException{
		DbFriends f = db.findFirst(Selector.from(DbFriends.class).where("owenrId", "=", owenrId)
				.and(WhereBuilder.b("friendId", "=", friend.getFriend().getObjectId())));
		DbFriends nf = new DbFriends(friend,owenrId);
		if (null!=f) {
			nf.setId(f.getId());
		}
		db.saveOrUpdate(nf);
		db.saveOrUpdate(new DbUser(friend.getFriend()) );
	}
	public static void saveFriend(List<Friends> friends,String owenrId) throws DbException{
		for(int i=0;i<friends.size();i++){
			saveFriend(friends.get(i), owenrId);
		}
		
	}
	
	public static List<Friends> getFriendList(String owenrId) throws DbException{
		List<DbFriends> dfs = db.findAll(Selector.from(DbFriends.class).where("owenrId","=",owenrId));
		List<Friends> fs=null;
		if (dfs!=null) {
			fs = DbFriends.toFriendList(dfs);
		}
		return fs;
	}
	
	public static Friends getFriendInfo(String owenrId,String fid) throws DbException{
		DbFriends dfd = db.findFirst(Selector.from(DbFriends.class).where("owenrId","=",owenrId).and("friendId", "=", fid));
		if (dfd!=null) {
			return dfd.toFriends();
		}
		return null;
	}
	
	
	public static ArrayList<DbFriends> getFriend(String owenrId,List<BmobIMConversation> cons){
		ArrayList<DbFriends> res = new ArrayList<DbFriends>();
		for (int i = 0; i < cons.size(); i++) {
			BmobIMConversation c = cons.get(i);
			try {
				DbFriends t = db.findFirst(Selector.from(DbFriends.class).where("owenrId","=",owenrId).and("friendId","=",c.getConversationId()));
				if (t!=null) {
					res.add(t);
				}
			} catch (DbException e) {
				e.printStackTrace();
			}
		}
		return res;
	}
	
	public static User getUserInfo(String oid){
		DbUser u=null;
		try {
			u=db.findFirst(Selector.from(DbUser.class).where("objectId","=",oid));
		} catch (DbException e) {
			e.printStackTrace();
		}
		if (u!=null) {
			return u.toUser();
		}
		return null;
	}
	
	public static void saveUser(User user){
		try {
			db.saveOrUpdate(new DbUser(user));
		} catch (DbException e) {
			e.printStackTrace();
		}
	}
	
}
